//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.agp.service.impl;

import com.agp.entity.AncientTree;
import com.agp.entity.TreeMedia;
import com.agp.mapper.TreeMapper;
import com.agp.mapper.TreeMediaMapper;
import com.agp.result.Result;
import com.agp.service.ExcelTreeDataImportService;
import com.agp.utils.AliOssUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelTreeDataImportServiceImpl implements ExcelTreeDataImportService {


    @Autowired
    private TreeMapper treeMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private TreeMediaMapper treeMediaMapper;

    @Transactional
    @Override
    public void importAncientTreeData(MultipartFile file) throws Exception {

        List<AncientTree> ancientTreeList = parseExcelFile(file);
        System.out.println(ancientTreeList);
        // 插入古树基本信息（会自动生成 tree_id）
        treeMapper.insertBatch(ancientTreeList);
        for (AncientTree ancientTree : ancientTreeList) {
            List<TreeMedia> treeMediaList = ancientTree.getImages();
            if (treeMediaList == null) {
                continue;
            }
            for (int i = 0; i < treeMediaList.size(); i++) {
                treeMediaList.get(i).setTreeId(ancientTree.getTreeId());
            }
            System.out.println(treeMediaList);
            treeMediaMapper.insertTreeMedia(treeMediaList);
        }


    }

    // 解析Excle 文件
    public List<AncientTree> parseExcelFile(MultipartFile file) {

        if (file == null) {
            return null;
        }

        List<AncientTree> ancientTreeList = new ArrayList<>();
        try {
            // 创建临时文件 ancient_tree_import-123456789.xlsx
            File tempFile = File.createTempFile("ancient_tree_import-", ".xlsx");
            // 确保应用退出时删除临时文件（可选）
            tempFile.deleteOnExit();

            // 保存上传的文件到临时文件
            file.transferTo(tempFile);
            // 使用 Apache POI 打开工作簿
            try (Workbook workbook = new XSSFWorkbook(tempFile)) {
                Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
                int lastRowNum = sheet.getLastRowNum();
                // 创建一个 Drawing 对象，用于处理图片
                XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
                // 遍历每一行，从第二行开始（第一行为表头）
                int count=0;
                for (int i = 1; i < lastRowNum; i++) {
                    count++;
                    // 获取每一行的数据
                    Row row = sheet.getRow(i);
                    if (row == null) continue;
                    AncientTree ancientTree = new AncientTree();
                    // 读取每一列的数据并赋值给 AncientTree 对象

                    ancientTree.setChineseName(row.getCell(0).getStringCellValue());   // chineseName
                    ancientTree.setScientificName(row.getCell(1).getStringCellValue()); // scientificName
                    ancientTree.setFamilyName(row.getCell(2).getStringCellValue());     // familyName
                    ancientTree.setGenusName(row.getCell(3).getStringCellValue());      // genusName
                    ancientTree.setEstimatedAge((short) row.getCell(4).getNumericCellValue()); // estimatedAge
                    ancientTree.setProtectionLevel((int) row.getCell(5).getNumericCellValue()); // protectionLevel
                    ancientTree.setGpsLongitude(row.getCell(6).getNumericCellValue());  // gpsLongitude
                    ancientTree.setGpsLatitude(row.getCell(7).getNumericCellValue());   // gpsLatitude
                    ancientTree.setLocationAddress(row.getCell(8).getStringCellValue()); // locationAddress
                    ancientTree.setDescription(row.getCell(9).getStringCellValue());    // description


                    ancientTree.setCreateTime(LocalDateTime.now());
                    ancientTree.setUpdateTime(LocalDateTime.now());

                    // 将 AncientTree 对象添加到列表中
                    ancientTreeList.add(ancientTree);
                }


                for (XSSFShape shape : drawing.getShapes()) {
                    if (shape instanceof XSSFPicture) {
                        XSSFPicture picture = (XSSFPicture) shape;
                        XSSFClientAnchor anchor = picture.getClientAnchor();
                        int col = anchor.getCol1();

                        if (col >= 10) { // 只处理第11列及以后的图片
                            int rowImage = anchor.getRow1(); // 获取图片所在行号（从0开始）

                            if (rowImage >= 1 && rowImage <= ancientTreeList.size()) {
                                AncientTree tree = ancientTreeList.get(rowImage - 1); // 行号与列表对齐（跳过标题行）
                                byte[] imageBytes = picture.getPictureData().getData();

                                // 上传图片并获得 URL
                                String imageUrl = aliOssUtil.uploadFile(imageBytes, "admin");

                                // 构造 TreeMedia 对象并插入数据库
                                TreeMedia treeMedia = TreeMedia.builder()
                                        .treeId(tree.getTreeId())
                                        .mediaUrl(imageUrl)
                                        .mediaType(TreeMedia.MediaType.IMAGE)
                                        .createdTime(LocalDateTime.now())
                                        .build();
                                // 添加到对应 AncientTree 的 mediaList 中
                                if (tree.getImages() == null) {
                                    tree.setImages(new ArrayList<>());
                                }
                                tree.getImages().add(treeMedia);
                            }
                        }
                    }
                }
                System.out.println("djjdfjdjj"+count);
            } finally {
                if (tempFile != null && tempFile.exists()) {
                    if (!tempFile.delete()) {
                        System.err.println("无法删除临时文件：" + tempFile.getAbsolutePath());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Result.error("文件处理失败: " + e.getMessage());
        } catch (InvalidFormatException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
        return ancientTreeList;
    }

}
